package com.liyuanjinglyj.gifcard;

import com.liyuanjinglyj.gifcard.slice.ChoiceImageAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentProvider;
import ohos.agp.components.Image;
import ohos.agp.utils.Color;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.Revocable;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;
import ohos.utils.zson.ZSONObject;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

public class ChoiceImageAbility extends Ability {
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x0001, "选择图片测试");
    private Button button;
    private long formId;
    private final  int imgRequestCode=123;
    private ImageSource imageSource = null;
    private PixelMap pixelMap=null;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_choice_image);
        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(Color.BLACK.getValue());

        formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, -1);
        requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE"},imgRequestCode);
        this.button=(Button)findComponentById(ResourceTable.Id_ability_choice_image_button);
        this.button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent = new Intent();
                Operation opt=new Intent.OperationBuilder().withAction("android.intent.action.GET_CONTENT").build();
                intent.setOperation(opt);
                intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
                intent.setType("image/*");
                startAbilityForResult(intent, imgRequestCode);
            }
        });
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        if(requestCode==imgRequestCode)
        {
            HiLog.info(label,"选择图片getUriString:"+resultData.getUriString());
            String chooseImgUri=resultData.getUriString();
            HiLog.info(label,"选择图片getScheme:"+chooseImgUri.substring(chooseImgUri.lastIndexOf('/')));
            DataAbilityHelper helper=DataAbilityHelper.creator(getContext());
            String chooseImgId=null;
            if(chooseImgUri.lastIndexOf("%3A")!=-1){
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf("%3A")+3);
            }
            else {
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf('/')+1);
            }
            Uri uri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,chooseImgId);
            HiLog.error(label,"选择图片dataability路径:"+uri.toString());
            TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            Revocable revocable = globalTaskDispatcher.asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileDescriptor fd = helper.openFile(uri, "r");
                        imageSource = ImageSource.create(fd, null);
                        pixelMap = imageSource.createPixelmap(null);
                        getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                ComponentProvider componentProvider = new ComponentProvider(ResourceTable.Layout_form_grid_pattern_widget_2_2, getContext());
                                componentProvider.setPixelMap(ResourceTable.Id_form_grid_pattern_widget_image,"setPixelMap", pixelMap);
                                try {
                                    updateForm(formId,componentProvider);
                                } catch (FormException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (imageSource != null) {
                            terminateAbility();
                        }
                    }
                }
            });

        }
    }
}

/****
 FileDescriptor fd = helper.openFile(uri, "r");
 imageSource = ImageSource.create(fd, null);
 pixelMap = imageSource.createPixelmap(null);
 ComponentProvider componentProvider = new ComponentProvider(ResourceTable.Layout_form_grid_pattern_widget_2_2, getContext());
 componentProvider.setPixelMap(ResourceTable.Id_form_grid_pattern_widget_image,"setPixelMap", pixelMap);
 updateForm(formId,componentProvider);
 *
 *
 HiLog.info(label,"私有目录:"+this.getFilesDir());
 HiLog.info(label,"缓存目录:"+this.getCacheDir());
 HiLog.info(label,"数据目录:"+this.getDataDir());
 HiLog.info(label,"外部目录:"+this.getExternalCacheDir());
 HiLog.info(label,"引用目录:"+this.getPreferencesDir());
 HiLog.info(label,"同步目录:"+this.getDistributedDir());
 HiLog.info(label,"应用目录:"+this.getDir("", Context.MODE_PRIVATE));
 *
 *
 FileDescriptor fd = helper.openFile(uri, "r");
 ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
 sourceOptions.formatHint = "image/jpeg";
 imageSource = ImageSource.create(fd, sourceOptions);
 //创建位图
 ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
 decodingOpts.desiredSize = new Size(200, 200);
 decodingOpts.desiredPixelFormat= PixelFormat.RGB_565;
 PixelMap pixelMap = imageSource.createPixelmap(decodingOpts);
 */
